package com.woniuxy.yogaapp.realm;

import java.util.HashSet;
import java.util.Set;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.context.annotation.Scope;
import com.woniuxy.yogaapp.pojo.User;
import com.woniuxy.yogaapp.service.UserService;

@Scope("prototype")
public class UserRealm extends AuthorizingRealm {
	@Resource
	private UserService userService;

	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		System.out.println("正在从数据库查询当前用户的角色 和权限");
		// 模拟从数据库查询当前用户的角色/权限
		// 得到账号
		String account = (String) principals.getPrimaryPrincipal();
		// 用于存放数据库找那个查询出的当前用户有哪些角色
		User user=new User();
		user.setAccount(account);
		//调用查询方法
		String role=userService.findRoleByAccount(user);
		Set<String> roles = new HashSet<>();
		roles.add(role);// 假设查询出的是admin
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
		// 根据角色查询当前角色的权限
		// Set<String> perms = new HashSet<>();
		// perms.add("user:delete");
		// info.addStringPermissions(perms);

		return info;
	}

	/**
	 * 认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("正在进行认证");
		// 如果该方法的返回值为null，代表没有在数据库中查询到该账户
		// 获取用户提交的账号
		String account = (String) token.getPrincipal();
		// 获取密码
		String pwd = new String((char[]) token.getCredentials());
		// 通过账号从数据库中查询出数据
		User user = new User();
		user.setAccount(account);
		User resultUser = userService.login(user);
		// 1.获取subject对象

		Subject currentUser = SecurityUtils.getSubject();
		Session session = currentUser.getSession();
		if(	session.getAttribute("uid")!=null){
			session.removeAttribute("uid");
		}
		session.setAttribute("uid", resultUser.getUid());
		// 获取
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(resultUser.getAccount(), resultUser.getPass(),
				getName());
		return info;
	}
}
